package yunhe.servlet;

import yunhe.service.BoardServers;
import yunhe.service.impl.BoardServersImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("serial")
public class EditBoard extends HttpServlet {

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String[] bnames = req.getParameterValues("bname");
		String[] strs = req.getParameter("isEditbid").split(";");
		List<String> updateBids = new ArrayList<String>(); // 要修改的bid集合
		List<String> delBids = new ArrayList<String>(); // 要删除的bid集合
		for (String str : strs) {
			if (str.indexOf("U") == 0) { // U表示要修改的
				updateBids.add(str.split(":")[1]);
			} else if (str.indexOf("D") == 0) {// D表示要删除的
				delBids.add(str.split(":")[1]);
			}
		}

		BoardServers bs = new BoardServersImpl();
		// 执行修改操作
		int re1 = 0;
		if (bnames != null) {
			Map<Integer, String> bid_bname = new HashMap<Integer, String>();
			for (int i = 0; i < bnames.length; i++) {
				bid_bname.put(Integer.parseInt(updateBids.get(i)), bnames[i]);
			}

			re1 = bs.updateBoard(bid_bname);
		}

		// 执行删除操作
		int re2 =0;
		if (!delBids.isEmpty()) { // 不为空，则有删除操作
			int[] bids = new int[delBids.size()];
			for (int i = 0; i < bids.length; i++) {
				bids[i] = Integer.parseInt(delBids.get(i));
			}
			re2 = bs.delBoard(bids);
		}
		
		String s="";
		HttpSession session = req.getSession();
		if (re1 > 0) {
			s+="updatesucc";
		}
		if (re2 > 0) {
			s+="deltesucc";
		}
		if (re1 <0) {
			s+="updatefail";
		}
		if (re2 <0) {
			s+="delfail";
		}
		session.setAttribute("isEditBoardSucc", s);// 修改成功
		resp.sendRedirect("GetBoard?flag=EditBoard");
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
}
